#include "InputHandler.h"

InputHandler::InputHandler(HINSTANCE hInstance, HWND hWnd)
{
	this->hWnd = hWnd;
	ZeroMemory(keyboardState, sizeof(keyboardState));					// set
	ZeroMemory(previousKeyboardState, sizeof(previousKeyboardState));	// memory
	ZeroMemory(&mouseState, sizeof(mouseState));						// locations
	ZeroMemory(&previousMouseState, sizeof(previousMouseState));		// to zero

	DirectInput8Create(hInstance,
					   DIRECTINPUT_VERSION,
					   IID_IDirectInput8,
					   (void**)&dInput,
					   0);

	dInput->CreateDevice(GUID_SysKeyboard, &keyboard, 0);
	keyboard->SetDataFormat(&c_dfDIKeyboard);
	keyboard->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
	keyboard->Acquire();

	dInput->CreateDevice(GUID_SysMouse, &mouse, 0);
	mouse->SetDataFormat(&c_dfDIMouse2);
	mouse->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
	mouse->Acquire();
}

InputHandler::~InputHandler()
{
	mouse->Unacquire();
	mouse->Release();
	mouse =0;

	keyboard->Unacquire();
	keyboard->Release();
	keyboard = 0;

	dInput->Release();
	dInput = 0;
}

void InputHandler::poll()
{
	memcpy(previousKeyboardState, keyboardState, sizeof(keyboardState)); // copy array directly from memory location
	HRESULT hr = keyboard->GetDeviceState(sizeof(keyboardState), (void**)keyboardState);
	if (FAILED(hr))
	{
		ZeroMemory(keyboardState, sizeof(keyboardState));
		keyboard->Acquire();
	}

	previousMouseState = mouseState;
	hr = mouse->GetDeviceState(sizeof(mouseState), (void**)&mouseState);
	if (FAILED(hr))
	{
		ZeroMemory(&mouseState, sizeof(mouseState));
		mouse->Acquire();
	}

	previousMousePosition = mousePosition;
	GetCursorPos(&mousePosition);
	ScreenToClient(hWnd, &mousePosition); // convert screen co-ords to window co-ords
}

bool InputHandler::isKeyDown(unsigned char key) const
{
	if ((keyboardState[key] & 0x80) != 0)
		return true;
	return false;
}

bool InputHandler::wasKeyDown(unsigned char key) const
{
	if ((previousKeyboardState[key] & 0x80) != 0)
		return true;
	return false;
}